package Forms;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;

import datatables.AbstractTable;

public class EntryAdderFrame extends JFrame {

	private JPanel contentPane;
	private JTable entryTable;
	private static Connection con = null;
	private Statement st = null;
	private ResultSet rs = null;
	private String[] columnNames;
	private String tableName;
	private int columns;
	private int errorColumn;
	private ResultSetMetaData metaData;
	private final int COLUMN_WIDTH = 100;
	private AbstractTable associatedTable;

	/**
	 * Create the frame. A small frame that lets you add an entry to the table
	 * selected in the adminframe,
	 */
	public EntryAdderFrame(AbstractTable _associatedTable, Connection con) {

		entryTable = new JTable();
		associatedTable = _associatedTable;
		tableName = associatedTable.getTableName();
		try {
			st = con.createStatement();
			rs = st.executeQuery("SELECT * FROM " + tableName);
			metaData = rs.getMetaData();
			columns = metaData.getColumnCount();
			String[] columnNamesBuffer = new String[columns];
			for (int i = 0; i < columnNamesBuffer.length; i++) {
				columnNamesBuffer[i] = metaData.getColumnName(i + 1);
			}
			columnNames = columnNamesBuffer;
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(this, e.getMessage());
		}

		Dimension preferredPanelSize = new Dimension(COLUMN_WIDTH * columns, 44);

		entryTable.setModel(new DefaultTableModel(columnNames, 1));

		entryTable.setMaximumSize(new Dimension(800, 100));
		entryTable.setPreferredSize(preferredPanelSize);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		JScrollPane scrollPane = new JScrollPane(entryTable);
		scrollPane
				.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
		scrollPane.setMaximumSize(new Dimension(800, 100));
		scrollPane.setPreferredSize(preferredPanelSize);

		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		contentPane.add(scrollPane, BorderLayout.NORTH);

		setContentPane(contentPane);

		JPanel buttonPanel = new JPanel();
		contentPane.add(buttonPanel, BorderLayout.SOUTH);
		// actionlistener that before adding the entry checks if the selected
		// column can be null, if not it warns you

		JButton addEntryButton = new JButton("Add Entry");
		addEntryButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				if (entryTable.getCellEditor() != null) {
					entryTable.getCellEditor().stopCellEditing();
				}
				String queryString = "INSERT INTO " + tableName + " VALUES (";
				Boolean submittable = false;
				for (int i = 0; i < columns; i++) {
					submittable = checkData(i);
					if (submittable) {
						queryString = queryString + (getCellContent(i, 0));
						if (i == columns - 1) {
							queryString = queryString + (");");
						} else {
							queryString = queryString + (", ");
						}
					} else {
						JOptionPane.showMessageDialog(contentPane,
								columnNames[errorColumn] + " can't be empty!");
						break;
					}
				}
				try {
					st.executeUpdate(queryString);
					associatedTable.refreshTable();
					dispose();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});
		buttonPanel.add(addEntryButton);

		JButton cancelButton = new JButton("Cancel");
		cancelButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});
		buttonPanel.add(cancelButton);

		this.pack();
		this.setVisible(true);

	}
//nullable check
	public boolean checkData(int column) {
		boolean submittable = true;
		try {
			if (metaData.isNullable(column + 1) == 0
					&& getCellContent(column, 0) == null) {
				errorColumn = column;
				submittable = false;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(this, e.getMessage());
		}
		return submittable;
	}
//get cellcontent in string format, parse for every datatype used
	public String getCellContent(int column, int row) {

		if (entryTable.getValueAt(row, column) == null) {
			return null;
		}
		switch (entryTable.getValueAt(row, column).getClass().toString()) {

		case "class java.lang.String":
			return "'" + entryTable.getValueAt(row, column).toString() + "'";

		case "class java.lang.Float":
			return Float.toString((Float) entryTable.getValueAt(row, column));

		case "class java.sql.Timestamp":
			return "TO_TIMESTAMP('"
					+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.s")
							.format((Timestamp) entryTable.getValueAt(row,
									column)) + "', 'DD-MON-YYYY HH24:MI:SS')";
		case "class java.sql.Date":
			return "TO_DATE('"
					+ new SimpleDateFormat("yyyy-MM-dd")
							.format((Date) entryTable.getValueAt(row, column))
					+ "', 'DD-MON-YYYY')";
		default:
			JOptionPane.showMessageDialog(entryTable, "Filetype unknown!");
			return null;

		}
	}

}
